package com.example.learn_gl_android.model


import android.opengl.GLSurfaceView.Renderer
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import java.nio.IntBuffer
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

class SixPointedStarGLViewRenderer : Renderer
{

    val mTriangleVertex : FloatArray = floatArrayOf(
        0.1f, 0.6f, 0.0f,
        -0.3f,0.0f, 0.0f,
        0.3f, 0.1f, 0.0f)
    val mTriangleColor : IntArray = intArrayOf(
        65535, 0, 0, 0,
        0, 65535, 0, 0,
        0, 0, 65535, 0
    )

    val mTriangleVertexBuffer : FloatBuffer
    val mTriangleColorBuffer : IntBuffer

    init {

        mTriangleVertexBuffer = initBufferF(mTriangleVertex)
        mTriangleColorBuffer = initBuffer(mTriangleColor)
    }

    override fun onSurfaceCreated(gl: GL10?, cfg: EGLConfig?) {
        gl?.glDisable(GL10.GL_DITHER)
        gl?.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST)
        gl?.glClearColor(1f, 0f, 0f, 0f)
        gl?.glShadeModel(GL10.GL_SMOOTH)
        gl?.glEnable(GL10.GL_DEPTH_TEST)
        gl?.glDepthFunc(GL10.GL_LEQUAL)
    }

    override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
        gl?.glViewport(0,0, width, height)
        gl?.glMatrixMode(GL10.GL_PROJECTION)
        gl?.glLoadIdentity()
        val ratio  =  (width/height).toFloat()
        gl?.glFrustumf(-ratio, ratio, -1f, 1f, 1f, 10f)
    }

    override fun onDrawFrame(gl: GL10?) {
        gl?.glClear(GL10.GL_DEPTH_BUFFER_BIT or GL10.GL_COLOR_BUFFER_BIT)
        gl?.glEnableClientState(GL10.GL_VERTEX_ARRAY)
        gl?.glEnableClientState(GL10.GL_COLOR_ARRAY)
        gl?.glMatrixMode(GL10.GL_MODELVIEW)


        gl?.glLoadIdentity()
        gl?.glTranslatef(-0.32f, 0.35f, -1.2f)
        gl?.glVertexPointer(3, GL10.GL_FLOAT, 0, mTriangleVertexBuffer)
        gl?.glColorPointer(4, GL10.GL_FIXED, 0, mTriangleColorBuffer)
        gl?.glDrawArrays(GL10.GL_TRIANGLES, 0, 3)
        gl?.glClearColor(1.0f, 0.0f, 0.0f , 1.0f)
        gl?.glClear(GL10.GL_COLOR_BUFFER_BIT)

        gl?.glFinish()
        gl?.glDisableClientState(GL10.GL_COLOR_ARRAY)
        gl?.glDisableClientState(GL10.GL_VERTEX_ARRAY)
    }

    fun initBuffer(array: IntArray) : IntBuffer {
        var mBuffer : IntBuffer
        val byteBuffer = ByteBuffer.allocateDirect(array.size * 4)
        byteBuffer.order(ByteOrder.nativeOrder())
        mBuffer = byteBuffer.asIntBuffer()
        mBuffer.put(array)
        mBuffer.position(0)
        return mBuffer
    }

    fun initBufferF(array: FloatArray) : FloatBuffer {
        var mBuffer : FloatBuffer
        val byteBuffer = ByteBuffer.allocateDirect(array.size * 4)
        byteBuffer.order(ByteOrder.nativeOrder())
        mBuffer = byteBuffer.asFloatBuffer()
        mBuffer.put(array)
        mBuffer.position(0)
        return mBuffer
    }
}